package io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * socket 服务端
 *
 * @author verlet
 * @date 2020/2/28
 */
@Slf4j
public class Server {

    private static final int BYTE_SIZE = 1024 * 1024 * 4;
    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    static class MyThread extends Thread {
        private final Socket clientSocket;

        MyThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            try (InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream = clientSocket.getOutputStream()) {
                byte[] bytes = new byte[BYTE_SIZE];
                log.info("{} ===> 客户端开始发送消息： ", Thread.currentThread());
                int n;
                while ((n = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, n);
                    log.info(Thread.currentThread() + new String(bytes, 0, n, StandardCharsets.UTF_8));
                }
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void server(int port) {

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            log.info("服务端启动成功。。。");
            while (true) {
                log.info("等待客户连接。。。");
                Socket clientSocket = serverSocket.accept();
                log.info("客户端连接成功。。。 {}", clientSocket.getPort());
                executorService.execute(new MyThread(clientSocket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Server().server(5201);
    }
}
